import {$notice, createHttp, iHttpRequestConfig} from "plain-design";
import {env} from "../../env";
import {LoginService} from "../../common/LoginService";

export const http = createHttp({
  baseURL: env.baseURL
});

http.interceptors.request.use(async (requestConfig) => {
  if (!requestConfig.noToken) {
    if (!requestConfig.headers?.['Authorization']) {
      requestConfig.headers['Authorization'] = (await LoginService.getToken()).token;
    }
  }
  return requestConfig;
});

http.interceptors.response.use(
  resp => {
    const { data } = resp;

    /*后端响应失败*/
    if (data.fail) {
      const requestConfig = resp.config as iHttpRequestConfig<any> | undefined;
      return handleErrorResponse(data, requestConfig);
    }
    return Object.assign({ ...data }, { _resp: resp });
  },
  (error) => {
    console.error(error);
    const requestConfig = error.config as iHttpRequestConfig<any> | undefined;
    return handleErrorResponse(error, requestConfig);
  }
);

const handleErrorResponse = (error: any, requestConfig: iHttpRequestConfig<any> | undefined) => {
  if (!!error.response?.data) {
    error = error.response?.data;
  }
  /*自动处理错误，没有requestConfig证明代码执行异常，也要显示提示*/
  if (!requestConfig || requestConfig.autoHandleError != false) {
    let message = typeof error === "string" ? error : (error.message || error.error || error);
    if (typeof message !== "string") {
      message = JSON.stringify(message);
    }
    $notice.error(message);
  }

  return Promise.reject(error);
};

declare module 'axios' {
  export interface AxiosRequestConfig {
    noToken?: boolean;
  }
}
